package test;

import java.util.Optional;

/**
 * @program: javase
 * @description: Optional类避免空指针
 * @author: lld
 * @create: 2020-11-24 16:06
 **/
public class OptionalClass {
    public static void main(String[] args) {
        Boy boy = new Boy("mmm");
        boy=null;//置空
        Optional<Boy> optionalBoy = Optional.ofNullable(boy);
        System.out.println(optionalBoy);
        //为空则用后面的替换
        Boy bbb = optionalBoy.orElse(new Boy("bbb"));
        System.out.println(bbb);
    }
}
class Boy{
    private String name;

    @Override
    public String toString() {
        return "test.Boy{" +
                "name='" + name + '\'' +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Boy(String name) {
        this.name = name;
    }
}
